<?php
/* --------------------------------------------------------------
   AdminWriter.php 2023-06-13
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2023 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

declare(strict_types=1);

namespace Gambio\Admin\Modules\Admin\App\Data;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;
use Gambio\Admin\Modules\Admin\Model\Admin;
use Gambio\Admin\Modules\Admin\Services\Exceptions\StorageOfAdminsFailedException;

/**
 * Class AdminWriter
 *
 * @package Gambio\Admin\Modules\Admin\App\Data
 */
class AdminWriter
{
    /**
     * @var Connection
     */
    private $db;
    
    
    /**
     * AdminWriter constructor.
     *
     * @param Connection $db
     */
    public function __construct(Connection $db)
    {
        $this->db = $db;
    }
    
    
    /**
     * @param Admin ...$admins
     *
     * @return int[]
     *
     * @throws StorageOfAdminsFailedException|Exception
     */
    public function storeAdmins(Admin ...$admins): array
    {
        $ids = [];
        $this->db->beginTransaction();
        
        try {
            foreach ($admins as $admin) {
                $this->updateAdmin($admin);
                $ids[] = $admin->id();
            }
            
            $this->db->commit();
        } catch (Exception $exception) {
            $this->db->rollBack();
            
            throw StorageOfAdminsFailedException::becauseOfException($exception);
        }
        
        return $ids;
    }
    
    
    /**
     * @param Admin $admin
     *
     * @throws Exception
     */
    private function updateAdmin(Admin $admin): void
    {
        $this->db->createQueryBuilder()
            ->delete('admin_access_users')
            ->where('customer_id = :id')
            ->setParameter('id', $admin->id())
            ->executeQuery();
        
        foreach ($admin->assignedRoleIds() as $assignedRoleId) {
            $this->db->createQueryBuilder()
                ->insert('admin_access_users')
                ->setValue('customer_id', ':adminId')
                ->setValue('admin_access_role_id', ':roleId')
                ->setParameter('adminId', $admin->id())
                ->setParameter('roleId', $assignedRoleId->value())
                ->executeQuery();
        }
    }
}